package com.tools.scanner.viewmodel

import androidx.lifecycle.OnceLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.tools.scanner.bean.ApiResponse
import com.tools.scanner.bean.TranslatorInfo
import com.tools.scanner.network.IServerApi
import com.tools.scanner.network.RetrofitImpl
import com.tools.scanner.utils.DataReportUtil
import com.tools.scanner.viewmodel.DataViewModel.LoadStatus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class TranslatorViewModel : ViewModel() {

    private val mApiServer = RetrofitImpl.createApiService(IServerApi::class.java)
    private val mGson = Gson()

    val translatorLiveData = OnceLiveData<TranslatorInfo?>()

    fun translator(sourceCode: String, targetCode: String, textList: List<String>) {
        DataReportUtil.reportTranslator()
        viewModelScope.launch(Dispatchers.IO) {
            val jsonText = mGson.toJson(textList)

            val apiResponse: ApiResponse<List<String>>? = try {
                mApiServer.translator(sourceCode, targetCode, jsonText).execute().body()
            } catch (e: Exception) {
                e.printStackTrace()
                null
            }

            val result: TranslatorInfo? = if (apiResponse != null && apiResponse.isSuccess()) {
                TranslatorInfo(targetCode, apiResponse.data)
            } else {
                null
            }

            withContext(Dispatchers.Main) {
                translatorLiveData.value = result
            }
        }
    }

}